//
//  ViewController.swift
//  flutter_swift
//
//  Created by liuyaozong on 2021/8/10.
//

import UIKit
import flutter_boost
class ViewController: UIViewController {

    //同样声明一个对象用来存删除的函数
    var removeListener:FBVoidCallback?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的原生页面"
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        BoostDelegate.shared.navigationController = self.navigationController
        
        let btn1 = creatBtn(title: "跳转到首页")
        btn1.addTarget(self, action: #selector(clickHome), for: .touchUpInside)
        let btn2 = creatBtn(title: "跳转到我的")
        btn2.addTarget(self, action: #selector(clickMine), for: .touchUpInside)

        view.addSubview(btn1)
        view.addSubview(btn2)
        btn1.frame = .init(x: 100, y: 100, width: 100, height: 50)
        btn2.frame = .init(x: 100, y: 300, width: 100, height: 50)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
            FlutterBoost.instance().sendEventToFlutter(with: "eventToFlutter", arguments: ["data":"event from flutter"])
            print("已经向 flutter 发送了")
        }
        
        //这里注册事件监听，监听flutter发送到iOS的事件
        self.removeListener =  FlutterBoost.instance().addEventListener({[weak self] key, dic in
            //注意，如果这里self持有removeListener，而这个闭包中又有self的话，要用weak self
            //否则就有self->removeListener->self 循环引用
            
            //在这里处理你的事件
            print("接受到来自 flutter的事件");
            
        }, forName: "eventToNative")

        //在退出的时候解除注册(比如 deinit/dealloc 中)
//        removeListener?()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       
    }
    
    //跳转到首页
    @objc func clickHome() {
        let options = FlutterBoostRouteOptions()
        options.pageName = "homePage"
        
        BoostDelegate.shared.pushFlutterRoute(options)
    }
    
    //跳转到个人中心
    @objc func clickMine() {
        let options = FlutterBoostRouteOptions()
        options.pageName = "minePage"
        options.arguments = ["data": "床前明月光,疑是地上霜"]
        options.uniqueId = "举头望明月,低头思故乡"
        BoostDelegate.shared.pushFlutterRoute(options)
    }
    
    func creatBtn(title: String) -> UIButton {
        let btn = UIButton()
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(.black, for: .normal)
        return btn
    }

}

